<?php

namespace Protocols;

use \Workerman\Connection\ConnectionInterface;

class fsync
{
    public static function input($recv_buffer)
    {
        if(strlen($recv_buffer) < 12)
        {
            return 0;
        }

        $array = unpack("Ifilename_length/Qfilecontent_length", $recv_buffer);

        return 12 + array_sum($array);
    }

    public static function decode($recv_buffer)
    {
        $array = unpack("Ifilename_length/Qfilecontent_length", $recv_buffer);

        $data = [
            'filename' => substr($recv_buffer, 12, $array['filename_length']),
            'content'  => substr($recv_buffer, 12 + $array['filename_length'], $array['filecontent_length']),
        ];

        return $data;
    }

    public static function encode($data)
    {
        return pack("IQ", strlen($data['filename']), strlen($data['content'])) . $data['filename'] . $data['content'];
    }
}
